import { defineStore } from 'pinia'
import { getCategoryList } from '@/api/category'

export const useAppStore = defineStore('app', {
  state: () => ({
    categoryModalVisible: false,
    announcementModalVisible: false,
    showCategoryFab: false,
    categories: [{ id: 'all', name: '全部', icon: 'Menu' }],
    activeCategoryId: 'all',
    userInfo: {
      id: 1,
      username: 'fan',
      avatar: 'https://blog-fan.oss-cn-beijing.aliyuncs.com/avatar/girl.png',
    },
  }),
  getters: {
    activeCategory: (state) => {
      return state.categories.find((c) => c.id === state.activeCategoryId) || state.categories[0]
    },
  },
  actions: {
    async fetchCategories() {
      try {
        const list = await getCategoryList()
        this.categories = [{ id: 'all', name: '全部', icon: 'Menu' }, ...list]
        const exists = this.categories.some((c) => c.id === this.activeCategoryId)
        if (!exists) this.activeCategoryId = 'all'
      } catch {
        // 失败时保留“全部”，不抛出
        this.categories = [{ id: 'all', name: '全部', icon: 'Menu' }]
      }
    },
    toggleCategoryModal() {
      this.categoryModalVisible = !this.categoryModalVisible
    },
    toggleAnnouncementModal() {
      this.announcementModalVisible = !this.announcementModalVisible
    },
    setActiveCategoryId(categoryId) {
      this.activeCategoryId = categoryId
      this.categoryModalVisible = false
    },
    selectCategoryAndCloseModal(categoryId) {
      this.activeCategoryId = categoryId
      this.categoryModalVisible = false
    },
    setCategoryFabVisible(visible) {
      this.showCategoryFab = visible
    },
  },
})
